package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"post-mgr/appconfig"
	"sync"
)

var DB *gorm.DB

func Init() {
	var err error
	mysqlConfig := appconfig.Config.Mysql
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConfig.User, mysqlConfig.Password, mysqlConfig.Host, mysqlConfig.Port, mysqlConfig.Database)
	once := sync.Once{}
	once.Do(func() {
		DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})
	if err != nil {
		panic("mysql connect failed")
	}
	fmt.Println("mysql connect success")
	err = DB.AutoMigrate(&User{}, &Post{})
	if err != nil {
		panic("mysql migrate failed")
	}
	fmt.Println("mysql migrate success")
}
